/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.www.interfaces.nodeactions;

import com.velocityme.entity.Activity;
import com.velocityme.entity.Contactable;
import com.velocityme.entity.Node;
import com.velocityme.entity.Time;
import com.velocityme.session.ActivityLocal;
import com.velocityme.session.KeyLocal;
import com.velocityme.session.NodeLocal;
import com.velocityme.www.actionforms.ChangeStateActionForm;
import com.velocityme.www.actionforms.TimeActionForm;
import com.velocityme.www.actionforms.TimeIdActionForm;
import com.velocityme.www.dto.IdName;
import com.velocityme.www.utility.NodeUtil;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author rcrida
 */
public class ActivityActions extends TaskActions {

    protected void configureCreate(HttpSession session, KeyLocal key) {
        session.setAttribute("priorityPairs", NodeUtil.getInstance().getPriorityPairs());
        session.setAttribute("completePairs", NodeUtil.getInstance().getPercentageCompletes());
        session.setAttribute("taskTypePairs", NodeUtil.getAllTaskTypePairs(key));
        session.setAttribute("allContactablePairs", NodeUtil.getAllContactablePairs(key));
        session.setAttribute("days", NodeUtil.getInstance().getDurationDays());
        session.setAttribute("hours", NodeUtil.getInstance().getDurationHours());
        session.setAttribute("minutes", NodeUtil.getInstance().getMinutes());
    }

    protected void configureEdit(HttpSession session, KeyLocal key, Activity activity) {
        session.setAttribute("priorityPairs", NodeUtil.getInstance().getPriorityPairs());
        session.setAttribute("completePairs", NodeUtil.getInstance().getPercentageCompletes());
        session.setAttribute("taskTypePairs", NodeUtil.getAllTaskTypePairs(key));
        session.setAttribute("personPairs", NodeUtil.getAllPersonPairs(key));
        session.setAttribute("days", NodeUtil.getInstance().getDurationDays());
        session.setAttribute("hours", NodeUtil.getInstance().getDurationHours());
        session.setAttribute("minutes", NodeUtil.getInstance().getMinutes());
        session.setAttribute("allContactablePairs", NodeUtil.getAllContactablePairs(key));
        Collection<IdName> interestedContactablePairs = new ArrayList<IdName>();
        for (Contactable contactable: activity.getInterestedContactables()) {
            interestedContactablePairs.add(new IdName(contactable.getId(), contactable.toString()));
        }
        session.setAttribute("interestedContactablePairs", interestedContactablePairs);
        Collection<IdName> responsibleContactablePairs = new ArrayList<IdName>();
        for (Contactable contactable: activity.getResponsibleContactables()) {
            responsibleContactablePairs.add(new IdName(contactable.getId(), contactable.toString()));
        }
        session.setAttribute("responsibleContactablePairs", responsibleContactablePairs);

    }

    public ActionForward changeState(ActionMapping mapping,
                                     ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        ChangeStateActionForm changeStateAF = (ChangeStateActionForm)form;
        Long nodeId = (Long)session.getAttribute("nodeId");
        if (request.getParameter("btnSubmit").equals("OK")) {
            long transitionId = changeStateAF.getTransitionId();
            byte percentageComplete = changeStateAF.getPercentageComplete();
            String message = changeStateAF.getDescription();
            File file = new File(changeStateAF.getFile().getFileName());
            String contentType = changeStateAF.getFile().getContentType();
            InputStream stream = changeStateAF.getFile().getInputStream();
            lookupActivityBean().changeState(key, nodeId, transitionId, message, percentageComplete, file, contentType, stream);

            if (changeStateAF.isAssignTime()) {
                Time timeValue = new Time();
                changeStateAF.extractTime(key, timeValue);
//                cs.taskTimeAssign(key, taskPK, percentageComplete, timeValue);
            }
        }
        request.setAttribute("nodeId", nodeId);
        return mapping.findForward("ACTION_SUCCESS");
    }

    public ActionForward showCreateTime(ActionMapping mapping,
                                        ActionForm form,
                                        HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
        Long nodeId = (Long)request.getAttribute("nodeId");
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        session.setAttribute("time", new Time());
        Activity activity = lookupActivityBean().findActivity(key, nodeId);
        session.setAttribute("statePairs", NodeUtil.getAllStatePairs(key));
        session.setAttribute("completePairs", NodeUtil.getInstance().getPercentageCompletes());
        session.setAttribute("years", NodeUtil.getInstance().getYears());
        session.setAttribute("months", NodeUtil.getInstance().getMonths());
        session.setAttribute("days", NodeUtil.getInstance().getDays());
        session.setAttribute("hours", NodeUtil.getInstance().getHours());
        session.setAttribute("durationDays", NodeUtil.getInstance().getDurationDays());
        session.setAttribute("durationHours", NodeUtil.getInstance().getDurationHours());
        session.setAttribute("minutes", NodeUtil.getInstance().getMinutes());
        // setup default values
        Date now = new Date();
        TimeActionForm timeAF = new TimeActionForm();
        timeAF.setActivityId(activity.getId());
        timeAF.setPercentageComplete(activity.getPercentageComplete());
        timeAF.setDurationTotalMins(activity.getRemainingDuration_min());
        timeAF.setStartDate(now);
        timeAF.setStopDate(now);
        timeAF.setStateId(activity.getState().getId());
        session.setAttribute("timeAF", timeAF);
        return mapping.findForward("ACTION_TIME_EDIT");
    }

    public ActionForward timeEdit(ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        TimeActionForm timeAF = (TimeActionForm)form;
        Long nodeId = (Long)session.getAttribute("nodeId");
        if (request.getParameter("btnSubmit").equals("OK")) {
            Time time = (Time)session.getAttribute("time");
            timeAF.extractTime(key, time);
            if (time.getId() != null) {
                lookupActivityBean().editTime(key, time, timeAF.getPercentageComplete());
            }
            else {
                lookupActivityBean().createTime(key, time, timeAF.getPercentageComplete());
            }
        }
        request.setAttribute("nodeId", nodeId);
        Node node = lookupNodeBeanLocal().findNode(key, nodeId);
        if (node instanceof Activity)
            return mapping.findForward("ACTION_TASK_TIME_SUCCESS");
        else
            return mapping.findForward("ACTION_PERSON_TIME_SUCCESS");
    }

    public ActionForward timeDeleteCheck(ActionMapping mapping,
                                         ActionForm form,
                                         HttpServletRequest request,
                                         HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        session.setAttribute("time", form);
        return mapping.findForward("ACTION_TIME_DELETE");
    }

    public ActionForward timeDelete(ActionMapping mapping,
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
        if (request.getParameter("btnSubmit").equals("OK")) {
            lookupActivityBean().deleteTime(key, ((TimeIdActionForm)form).getTimeId());
        }
        Long nodeId = (Long)session.getAttribute("nodeId");
        Node node = lookupNodeBeanLocal().findNode(key, nodeId);
        request.setAttribute("nodeId", nodeId);
        if (node instanceof Activity)
            return mapping.findForward("ACTION_TASK_TIME_SUCCESS");
        else
            return mapping.findForward("ACTION_PERSON_TIME_SUCCESS");
    }

    private ActivityLocal lookupActivityBean() {
        try {
            Context c = new InitialContext();
            return (ActivityLocal) c.lookup("java:comp/env/ActivityBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private NodeLocal lookupNodeBeanLocal() {
        try {
            Context c = new InitialContext();
            return (NodeLocal) c.lookup("java:comp/env/NodeBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
